package com.zsyh.jiujiu.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.example.zyh.toolslib.base.BaseFragment;
import com.example.zyh.toolslib.utils.SPUtils;
import com.example.zyh.toolslib.widget.TitleBar;
import com.google.gson.Gson;
import com.lwb.retrofit.RetrofitTask;
import com.ocnyang.cartlayout.bean.CartItemBean;
import com.ocnyang.cartlayout.bean.ICartItem;
import com.ocnyang.cartlayout.listener.CartOnCheckChangeListener;
import com.zsyh.jiujiu.Api;
import com.zsyh.jiujiu.R;
import com.zsyh.jiujiu.adepter.MainAdapter;
import com.zsyh.jiujiu.bean.GoodsBean;
import com.zsyh.jiujiu.bean.MyCarBean;
import com.zsyh.jiujiu.bean.NormalBean;
import com.zsyh.jiujiu.bean.OrderBuyBean;
import com.zsyh.jiujiu.bean.OrderListBean;
import com.zsyh.jiujiu.bean.ShopBean;
import com.zsyh.jiujiu.bean.SucessBean;
import com.zsyh.jiujiu.home.SureOrderActivity;
import com.zsyh.jiujiu.net.MyFragementObserver;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @ProjectName: livvehelp
 * @Package: com.zsyh.lsb.ui
 * @ClassName:
 * @Description: java类作用描述
 * @Author: zsyh
 * @CreateDate: 2020/9/7 11:59
 * @UpdateUser: liangwanbo
 * @UpdateDate: 2020/9/7 11:59
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class CarFragment extends BaseFragment {

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.rvlist)
    RecyclerView rvlist;
    @BindView(R.id.checkall)
    CheckBox checkall;
    @BindView(R.id.jioahuan)
    TextView jioahuan;
    @BindView(R.id.totlemoney)
    TextView totlemoney;
    @BindView(R.id.fuhao)
    TextView fuhao;
    @BindView(R.id.tv_totle)
    TextView tvTotle;
    private MainAdapter mAdapter;
    private int totalCount;//购物车商品ChildItem的总数量，店铺条目不计算在内
    private int totalCheckedCount;//勾选的商品总数量，店铺条目不计算在内
    private double totalPrice;//勾选的商品总价格
    private boolean isdelte;
    ArrayList<CartItemBean> cartItemBeans = new ArrayList<>();
    private String ids="";
    OrderListBean orderListBean;

    @Override
    protected int initLayout() {
        return R.layout.fragment_car;
    }

    @Override
    protected void initView(View rootView) {

    }

    @Override
    protected void initData() {
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isdelte=true;
                submitEvent();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        MYCar((String) SPUtils.get(getActivity(), "userid", ""));
    }

    @OnClick({R.id.checkall, R.id.jioahuan})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.checkall:
                mAdapter.checkedAll(((CheckBox)view).isChecked());
                break;
            case R.id.jioahuan:
                isdelte=false;
                submitEvent();
                break;
        }
    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给相关的 textView 进行数据填充
     */
    private void calculate() {
        orderListBean=new OrderListBean();
        List<OrderBuyBean> list=new ArrayList<>();
        totalCheckedCount = 0;
        totalCount = 0;
        totalPrice = 0.00;
        int notChildTotalCount = 0;
        if (mAdapter.getData() != null) {
            for (ICartItem iCartItem : mAdapter.getData()) {

                if (iCartItem.getItemType() == ICartItem.TYPE_CHILD) {
                    totalCount++;
                    if (iCartItem.isChecked()) {
                        totalCheckedCount++;
                        totalPrice += ((GoodsBean) iCartItem).getGoods_price() * ((GoodsBean) iCartItem).getGoods_amount();
                        ids+=((GoodsBean) iCartItem).getCarid()+",";
                        OrderBuyBean orderBuyBean=new OrderBuyBean();
                        orderBuyBean.setGoodid(((GoodsBean) iCartItem).getGoodid());
                        orderBuyBean.setNumber(((GoodsBean) iCartItem).getGoods_amount()+"");
                        orderBuyBean.setGoodmoney(((GoodsBean) iCartItem).getGoods_price()+"");
                        orderBuyBean.setImageurl(((GoodsBean) iCartItem).getImageurl());
                        orderBuyBean.setGoodname(((GoodsBean) iCartItem).getGoods_name());
                        orderBuyBean.setGooduserid(((GoodsBean) iCartItem).getGoodUserid());
                        orderBuyBean.setCarid(((GoodsBean) iCartItem).getCarid());
                        list.add(orderBuyBean);
                    }
                } else {
                    notChildTotalCount++;
                }
            }
            orderListBean.setData(list);
        }
        if (checkall.isChecked() && (totalCheckedCount == 0 || (totalCheckedCount + notChildTotalCount) != mAdapter.getData().size())) {
            checkall.setChecked(false);
        }
        if (totalCheckedCount != 0 && (!checkall.isChecked()) && (totalCheckedCount + notChildTotalCount) == mAdapter.getData().size()) {
            checkall.setChecked(true);
        }

        totlemoney.setText(totalPrice+"");
    }

    private void submitEvent() {

        if (totalCheckedCount == 0) {
            Toast.makeText(getActivity(), "你还没有选择任何商品", Toast.LENGTH_SHORT).show();
        } else {
           /* Toast.makeText(getActivity(),
                    new StringBuilder().append("你选择了").append(totalCheckedCount).append("件商品")
                            .append("共计 ").append(totalPrice).append("元"),
                    Toast.LENGTH_SHORT).show();*/
            if(isdelte){
                DeleteGood(ids.substring(0,ids.length()-1));
                mAdapter.removeChecked();
            }else{

                Bundle bundlegood = new Bundle();
                bundlegood.putString("data", orderListBean.toString());
                ActivityUtils.startActivity(bundlegood,SureOrderActivity.class);
            }

        }

    }



    /**
     * 购物车信息
     */
    public void MYCar(String userid){
        RetrofitTask.getInstance()
                .createApi(Api.class)
                .getGoodsById(userid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyFragementObserver(getActivity(),true) {
                    @Override
                    protected void onError(String errorMsg) {
                        Log.e("shopcarerror",errorMsg+"");
                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Log.e("shopcar",JsonStr+"");
                        Gson gson=new Gson();
                        MyCarBean myCarBean=gson.fromJson(JsonStr,MyCarBean.class);
                        if(cartItemBeans!=null){
                            cartItemBeans.clear();
                        }
                        NormalBean normalBean = new NormalBean();
                        normalBean.setMarkdownNumber(0);
                        cartItemBeans.add(normalBean);

                        for (int i=0;i<myCarBean.getData().size();i++){
                            ShopBean shopBean = new ShopBean();
                            shopBean.setShop_name(myCarBean.getData().get(i).getNickname());
                            shopBean.setItemType(CartItemBean.TYPE_GROUP);
                            cartItemBeans.add(shopBean);

                            for (int j = 0; j < myCarBean.getData().get(i).getGoodsList().size(); j++) {
                                MyCarBean.DataBean.GoodsListBean bean=myCarBean.getData().get(i).getGoodsList().get(j);
                                GoodsBean goodsBean = new GoodsBean();
                                goodsBean.setGoods_name(bean.getGoods_title());
                                goodsBean.setItemType(CartItemBean.TYPE_CHILD);
                                goodsBean.setItemId((j + 1) * 10 + j);
                                goodsBean.setGoods_price(bean.getGoods_price());
                                goodsBean.setGroupId(i);
                                goodsBean.setGoodid(bean.getGoodsId());
                                String[] split = bean.getGoods_pic().split("\\|");
                                goodsBean.setImageurl(split[0]);
                                goodsBean.setCarid(bean.getId());
                                goodsBean.setGoods_amount(bean.getNum());
                                goodsBean.setGoodUserid(myCarBean.getData().get(i).getGoodsList().get(0).getGoodsUserId());
                                cartItemBeans.add(goodsBean);
                            }
                        }
                        rvlist.setLayoutManager(new LinearLayoutManager(getActivity()));
                        mAdapter = new MainAdapter(getActivity(), cartItemBeans,getActivity());
                        mAdapter.setOnCheckChangeListener(new CartOnCheckChangeListener(rvlist, mAdapter) {
                            @Override
                            public void onCalculateChanged(ICartItem cartItemBean) {
                                calculate();
                            }
                        });
                        rvlist.setAdapter(mAdapter);
                    }
                });
    }

    /**
     * 删除
     */
    public void DeleteGood(String ids){
        RetrofitTask.getInstance()
                .createApi(Api.class)
                .deleteCar(ids)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyFragementObserver(getActivity(),false) {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Log.e("shanchu",JsonStr);
                        Gson gson=new Gson();
                        SucessBean sucessBean=gson.fromJson(JsonStr,SucessBean.class);
                        if(sucessBean.getCode()==0){
                            MYCar((String) SPUtils.get(getActivity(), "userid", ""));
                        }

                    }
                });
    }
}
